import json


class JSONSet(set):
    """可 JSON 序列化的集合类 - 简化版本"""

    def __repr__(self):
        return f"JSONSet({super().__repr__()})"

    # 不需要重写 __iter__，只需要提供序列化方法
    def __json_serializable__(self):
        """返回可序列化的数据"""
        return {"__type__": "JSONSet", "values": list(super().__iter__())}


class SetEncoder(json.JSONEncoder):
    def default(self, obj):
        if hasattr(obj, '__json_serializable__'):
            return obj.__json_serializable__()
        elif isinstance(obj, set):
            return {"__type__": "set", "values": list(obj)}
        return super().default(obj)


class SetDecoder:
    @staticmethod
    def decode(json_str):
        def object_hook(obj_dict):
            if isinstance(obj_dict, dict) and "__type__" in obj_dict:
                if obj_dict["__type__"] == "JSONSet":
                    return JSONSet(obj_dict["values"])
                elif obj_dict["__type__"] == "set":
                    return set(obj_dict["values"])
            return obj_dict

        return json.loads(json_str, object_hook=object_hook)


# 测试
if __name__ == "__main__":
    # 测试数据
    data = {
        "custom_set": JSONSet([1, 2, 3]),
        "regular_set": {4, 5, 6},
        "name": "test"
    }

    print("原始数据:", data)

    # 序列化
    json_str = json.dumps(data, cls=SetEncoder, indent=2)
    print("\n序列化结果:")
    print(json_str)

    # 反序列化
    restored = SetDecoder.decode(json_str)
    print("\n反序列化结果:")
    print(restored)
    print(f"custom_set 类型: {type(restored['custom_set'])}")
    print(f"regular_set 类型: {type(restored['regular_set'])}")